<script>
export default {
  name: 'Right',
}
</script>

<template>
  <Card style="height: 546px">
    <p class="title">程序员需求人数</p>
    <div class="header row">
      <span class="col col-1">时间</span>
      <span class="col col-2">地址</span>
      <span class="col col-1">需求人数</span>
    </div>
    <div class="content" ref="contentRef">
      <div class="content-wrap" ref="wrapRef" :style="{transform: `translateY(${transformY}px)`}">
        <div class="row" v-for="item in list" :key="item.id">
          <div class="col col-1">{{ item.date }}</div>
          <div class="col col-2">{{ item.address }}</div>
          <div class="col col-1">{{ item.num }}</div>
        </div>
      </div>
    </div>
  </Card>
</template>

<script setup>
import createWebSocket from '@/utils/web-socket'
import { onMounted, ref } from "vue";
import Card from '@/components/Card/index.vue'

const list = ref([])
onMounted(async () => {
  // 得到socket
  const socket = await createWebSocket()
  // 绑定接收消息的监听
  socket.onmessage = (event) => {
    // 读取返回的新列表
    const newList = JSON.parse(event.data)
    // 合并到当前List中
    list.value = list.value.concat(newList)
    // 如果列表项的个数超过20时, 开始滚动
    if (list.value.length>20) {
      startScroll()
    }
  }
})
let timer
const contentRef = ref()
const wrapRef = ref()
// 保存列表滑动的y轴坐标
const transformY = ref(0)

function startScroll() {
  // 清除前一个定时器
  if (timer) {
    clearInterval(timer)
  }
  // 启动一个循环定时器, 每次滚动一个非常小的距离
  // 每秒移动60次, 每次移动0.5px
  timer = setInterval(() => {

    let y = transformY.value
    y -= 2
    // 得到能滚动的最距离
    const maxDistance = wrapRef.value.clientHeight - contentRef.value.clientHeight
    // 当滚动实际距离超过, 就停止滚动
    if (-y >=maxDistance) {
      clearInterval(timer)
      timer = null
      // transformY.value = 0
    } else { // 否则继续
      transformY.value = y
    }
    
  }, 1000/60);
}


</script>

<style scoped lang="scss">
.title {
  text-align: center;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  margin: 10px 0;
}

.header {
  margin: 0 10px;
  background-color: rgba(255, 255, 255, 0.1);
  .col {
    color: #68d8fe;
  }
}

.content {
  margin: 0 10px;
  height: calc(100% - 68px);
  overflow: hidden;
}
.row {
  display: flex;
  padding: 4px 0;
  &:hover {
    background-color: rgba(255, 255, 255, 0.1);
    color: #68d8fe;
  }
  .col {
    color: #fff;
    text-align: center;
    font-size: 12px;
    color: #61a8ff;
    transform: scale(0.8);
  }
  .col-1 {
    flex: 1;
  }
  .col-2 {
    flex: 2;
  }
}

</style>